package hapi.db;

#if php
import php.db.Manager;
import php.db.Object;
#elseif neko
import neko.db.Manager;
import neko.db.Object;
#end

class PaginationManager<T:Object> extends Manager<T> {

	public function new(classval:Class<Object>) {
		super(classval);
	}
	
	public function getPage(conditions:{}, page:Int, perPage:Int, ?orderBy:String ):hapi.mvc.DisplayablePage {
		return this.getGenericPage(conditions, page, perPage, orderBy );
	}
	
	public function getTotalPages(conditions:{}, perPage:Int):Int {
		var  n = Math.ceil(this.count(conditions) / perPage);
		if (n < 1) n = 1;
		return n;
	}
	
	function getWithLimit(conditions:{}, rowCount:Int, offset:Int, ?orderBy):List<T> {
		var s = new StringBuf();
		s.add("SELECT * FROM ");
		s.add(table_name);
		s.add(" WHERE ");
		addCondition(s, conditions);
		if( orderBy != null)
			s.add(" ORDER BY "+orderBy);
		s.add(" LIMIT " + offset + ", " + rowCount);
		return objects(s.toString(),false);
	}
	
	function getGenericPage(conditions: { }, page:Int, perPage:Int, ?orderBy:String ) {
		if(Std.is(page, String)) page = Std.parseInt(cast page);
		var total = getTotalPages(conditions, perPage);
		var offset = (page - 1) * perPage;
		if ( page > total && total > 0) page = total;
		var items = getWithLimit(conditions, perPage, offset, orderBy );
		return new GenericObjectsPage<T>( items, page, total); 
	}
}